﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Notify.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysNotifyRepository : Repository<SysNotify, DefaultDbContext>
    {
        public SysNotifyRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SysNotifyRepository> logger)
           : base(dbContext, applicationContext)
        {
        }

        /// <summary>
        /// 分页获取系统通知
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageIndex">分页页数</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="limitReaderType">限制查看人类型(1：所有人可见 2：建设单位可见 3：总承包可见 4：专业分包可见 5：劳务公司可见)</param>
        /// <returns></returns>
        public IPagedList<SysNotify> GetSysNotifysByPage(NotifyQuery query, int pageIndex, int pageSize, int limitReaderType)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("sys_notify");
            if (limitReaderType != 0)
                sql.Where("limit_reader_type =@0", limitReaderType);
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(content Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.LimitReaderType.HasValue)
                sql.Where("limit_reader_type =@0", query.LimitReaderType);
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        /// <summary>
        /// 获取最新的系统公告
        /// </summary>
        /// <returns></returns>
        public SysNotify New()
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("sys_notify")
                .Where("limit_reader_type=1")
                .OrderBy("create_time DESC");
            string id = DbContext.FetchTop<string>(1, sql).FirstOrDefault() ?? "";
            return Get(id) ?? new SysNotify();
        }

        /// <summary>
        /// 获取置顶公告
        /// </summary>
        /// <returns></returns>
        public SysNotify TopNotify()
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("sys_notify")
                .Where("is_top=1")
                .OrderBy("create_time DESC");
            string id = DbContext.FetchTop<string>(1, sql).FirstOrDefault() ?? "";
            return Get(id) ?? new SysNotify();
        }
    }
}